/**
 * Alipay.com Inc. Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.study.util;


import com.study.bank.*;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
//import io.swagger.annotations.ApiModelProperty;


/**
 * @author wb-whl357206
 * @version $Id: DaoUtil.java, v 0.1 2018年03月07日 14:28 wb-whl357206 Exp $
 */
public class DaoUtil {

    private static String propertieStart = "";

    /**
     * <isNotEmpty prepend="," property="configDefaultValue">
     * config_default_value = #configDefaultValue#
     * </isNotEmpty>
     *
     * @param str
     * @param spilt
     */

    public static void str(String str, String spilt) {
        StringBuilder stringBuilder = new StringBuilder();
        if (null == str || str.length() == 0) {
            System.out.println("str为空");
        } else {
            String[] strData = str.split(spilt);
            for (int i = 0; i < strData.length; i++) {
                String propertyName = xxXxx(strData[i]);
                stringBuilder.append("<isNotEmpty prepend=\",\" property=\"")
                        .append(propertyName).append("\">")
                        .append("\n\r").append("   ").append(strData[i]).append(" ").append("=").append(" ")
                        .append("#").append(propertyName).append("#").append("\n\r").append("</isNotEmpty>").append("\n\r");
            }
        }
        System.out.println(stringBuilder);
    }

    /**
     * 下划线命名  转  驼峰命名
     *
     * @param propertyName
     * @return
     */
    public static String xxXxx(String propertyName) {
        String[] names = propertyName.split("_");
        StringBuilder stringBuilder = new StringBuilder(names[0]);
        for (int i = 1; i < names.length; i++) {
            stringBuilder.append(new String(names[i].charAt(0) + "").toUpperCase()).append(names[i].substring(1));
        }
        return stringBuilder.toString();
    }

    /**
     * 生成 类 封装到Map中的代码
     *
     * @param clazz         类 class 对象
     * @param type          为 true ,只按照propertyNames中的字段生成；为 false ,除了propertyNames中的字段其他的字段都生成
     * @param propertyNames
     * @Param classObjName 类对象变量名
     */
    public static void claasEncapsulationMap(Class clazz, boolean type, String... propertyNames) {
        List<String> file_names = new ArrayList<String>();
        StringBuilder stringBuilder = new StringBuilder("Map<String, Object> param = new HashMap<String, Object>();");
        stringBuilder.append("\r\n");
        String[] names = null;
        if (propertyNames != null) {
            names = new String[propertyNames.length];
            for (int i = 0; i < propertyNames.length; i++) {
                names[i] = propertyNames[i].toLowerCase();
            }
        } else {
            names = new String[0];
        }

        try {
            Field[] fields = clazz.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                field.setAccessible(true);
                String field_name = field.getName().toLowerCase();
                if (in_array(names, field_name) && true == type) {
                    stringBuilder.append("param.put(\"").append(field.getName()).append("\",").append(getSmallClassName(clazz))
                            .append(".").append(getGetMethod(clazz, field.getName()).getName()).append("());").append("\n\r");
                }
                if (in_array(names, field_name) == false && false == type) {
                    stringBuilder.append("param.put(\"").append(field.getName()).append("\",").append(getSmallClassName(clazz))
                            .append(".").append(getGetMethod(clazz, field.getName()).getName()).append("());").append("\n\r");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        System.out.println(stringBuilder);
    }

    /**
     * 生成 类 封装到Map中的代码
     *
     * @param clazz         类 class 对象
     * @param type          为 true ,只按照propertyNames中的字段生成；为 false ,除了propertyNames中的字段其他的字段都生成
     * @param propertyNames
     * @Param classObjName 类对象变量名
     */
    public static void claasEncapsulation(Class clazz, String target, boolean type, String... propertyNames) {
        List<String> file_names = new ArrayList<String>();
        StringBuilder stringBuilder = new StringBuilder("Map<String, Object> param = new HashMap<String, Object>();");
        stringBuilder.append("\r\n");
        String[] names = null;
        if (propertyNames != null) {
            names = new String[propertyNames.length];
            for (int i = 0; i < propertyNames.length; i++) {
                names[i] = propertyNames[i].toLowerCase();
            }
        } else {
            names = new String[0];
        }
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            try {
                field.setAccessible(true);
                String field_name = field.getName().toLowerCase();
                if ((in_array(names, field_name) == false && false == type) || (in_array(names, field_name) && true == type)) {
                    Method setMethod = getSetMethod(clazz, field.getName(), field);
                    Method getMehod = getGetMethod(clazz, field.getName());
                    if (setMethod != null && getMehod != null) {
                        stringBuilder.append(target).append(".").append(setMethod.getName()).append("(").append(getSmallClassName(clazz))
                                .append(".").append(getMehod.getName()).append("());").append("\n\r");
                    }
                }
            } catch (Exception e) {
                System.out.println(field.getName());
                throw new RuntimeException(e);
            }
        }

        System.out.println(stringBuilder);
    }

    /**
     * 生成 类 封装到Map中的代码
     *
     * @param clazz         类 class 对象
     * @param type          为 true ,只按照propertyNames中的字段生成；为 false ,除了propertyNames中的字段其他的字段都生成
     * @param propertyNames
     * @Param classObjName 类对象变量名
     */
    public static void createBeanChangeFunction(Class clazz, String target, boolean type, String... propertyNames) {
        List<String> file_names = new ArrayList<String>();
        StringBuilder stringBuilder = new StringBuilder("private").append(" ");
        String targetClassName = new String(target.charAt(0) + "").toUpperCase() + target.substring(1);
        stringBuilder.append(targetClassName);
        stringBuilder.append(" ").append(clazz.getSimpleName()).append("2").append(targetClassName);
        stringBuilder.append(" ").append("(").append(targetClassName).append(" ").append(target).append(") {");
        stringBuilder.append("\r\n");
        String[] names = null;
        if (propertyNames != null) {
            names = new String[propertyNames.length];
            for (int i = 0; i < propertyNames.length; i++) {
                names[i] = propertyNames[i].toLowerCase();
            }
        } else {
            names = new String[0];
        }
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            try {
                field.setAccessible(true);
                String field_name = field.getName().toLowerCase();
                if ((in_array(names, field_name) == false && false == type) || (in_array(names, field_name) && true == type)) {
                    Method setMethod = getSetMethod(clazz, field.getName(), field);
                    Method getMehod = getGetMethod(clazz, field.getName());
                    if (setMethod != null && getMehod != null) {
                        stringBuilder.append("  ").append(target).append(".").append(setMethod.getName()).append("(").append(getSmallClassName(clazz))
                                .append(".").append(getMehod.getName()).append("());").append("\n\r");
                    }
                }
            } catch (Exception e) {
                System.out.println(field.getName());
                throw new RuntimeException(e);
            }
        }
        stringBuilder.append("}");
        System.out.println(stringBuilder);
    }

    /**
     * java反射bean的get方法
     *
     * @param objectClass
     * @param fieldName
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Method getGetMethod(Class objectClass, String fieldName) {
        StringBuffer sb = new StringBuffer();
        sb.append("get");
        sb.append(fieldName.substring(0, 1).toUpperCase());
        sb.append(fieldName.substring(1));
        try {
            return objectClass.getMethod(sb.toString());
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * java反射bean的Set方法
     *
     * @param objectClass
     * @param fieldName
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Method getSetMethod(Class objectClass, String fieldName, Field field) {
        StringBuffer sb = new StringBuffer();
        sb.append("set");
        sb.append(fieldName.substring(0, 1).toUpperCase());
        sb.append(fieldName.substring(1));
        try {
            return objectClass.getMethod(sb.toString(), field.getType());
        } catch (Exception e) {
        }
        return null;
    }


    public static boolean in_array(String array[], String param) {
        for (String str : array) {
            if (str.equals(param)) {
                return true;
            }
        }
        return false;
    }

    public static String getSmallClassName(Class clazz) {
        String name = clazz.getName();
        String[] data = name.split("\\.");
        if (data.length > 0) {
            String smallName = data[data.length - 1];
            return smallName.substring(0, 1).toLowerCase() + smallName.substring(1);
        }

        return null;
    }

    /**
     * @param str   总字符串，以逗号分隔
     * @param spilt 开头分隔符
     * @param index 统一后缀
     * @param end   结尾符号
     */
    public static void strAppend(String str, String spilt, String index, String end) {
        str = str.replaceAll("\n", "");
        String[] strs = str.split(",");
        for (String s : strs) {
            String temp = s.substring(0, s.indexOf(":")).trim();
            StringBuilder stringBuilder = new StringBuilder(temp);
            stringBuilder.append(DaoUtil.propertieStart).append(spilt).append(index).append(temp).append(end);
            System.out.println(stringBuilder);
        }
    }

    public static boolean isTypeField(String fieldName) {
        if (null == fieldName) {
            return false;
        }
        String names[] = {"状态", "类型"};
        for (int i = 0; i < names.length; i++) {
            if (fieldName.indexOf(names[i]) > -1) {
                return true;
            }
        }
        return false;
    }

//    public static void createMessageEnum(Class clazz,Integer code,String ... out) {
//        Field[] fields = clazz.getDeclaredFields();
//        int n = code;
//        for (int i = 0; i < fields.length; i++) {
//            Field field = fields[i];
//            if(out != null && DataVerificationUtil.isArray(out,field.getName())) {
//                continue;
//            }
//
//            Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
//            String fieldContent = null;
//            for (int j = 0; j < declaredAnnotations.length; j++) {
//                Annotation declaredAnnotation = declaredAnnotations[j];
//                if(declaredAnnotation instanceof ApiModelProperty) {
//                    fieldContent = ((ApiModelProperty) declaredAnnotation).value().trim();
//                    if(fieldContent.split("：").length > 1) {
//                        fieldContent = fieldContent.split("：")[0].trim();
//                    }
//                    if(fieldContent.split(":").length > 1) {
//                        fieldContent = fieldContent.split(":")[0].trim();
//                    }
//                    if(fieldContent.split(" ").length > 1) {
//                        fieldContent = fieldContent.split(" ")[0].trim();
//                    }
//                }
//            }
//
//
//            List<String> enums = new ArrayList<String>();
//            enums.add(fieldContent+"不能为空");
//            if(isTypeField(fieldContent)) {
//                enums.add(fieldContent+"不合法");
//            }
//
//            String enFieldContent = YouDaoUtil.startTranscation(fieldContent);
//            String[] split = enFieldContent.split(" ");
//            if(split.length > 1) {
//                StringBuilder stringBuilder = new StringBuilder();
//                for (int j = 0; j < split.length; j++) {
//                    stringBuilder.append(split[j]);
//                    if(j != split.length - 1) {
//                        stringBuilder.append("_");
//                    }
//                }
//                enFieldContent = stringBuilder.toString();
//            }
//            List<String> enumsStuff = new ArrayList<String>();
//            enumsStuff.add(enFieldContent+"_CAN_NOT_NULL");
//            if(isTypeField(fieldContent)) {
//                enumsStuff.add(enFieldContent+"_ILLEGAL");
//            }
//
//            for (int j = 0; j < enums.size(); j++) {
//
//                String str = makeErrorEnumObj(n++,enumsStuff.get(j).toUpperCase(),enums.get(j)+"#"
//                        +YouDaoUtil.startTranscation(enums.get(j)));
////                String str = new StringBuilder(enumsStuff.get(j).toUpperCase()).append("(").append(n++).append(",\"")
////                        .append(enums.get(j)).append("#").append(YouDaoUtil.startTranscation(enums.get(j))).append("\"),").toString();
////
//                System.out.println(str);
//            }
//        }
//
//    }

    public static String makeErrorEnumObj(Integer code, String name, String desc) {
        return new StringBuilder(name).append("(").append(code).append(",\"")
                .append(desc).append("\"),").toString();
    }


    public static void main(String[] args) {

//      createMessageEnum(CreditCardPayDTO.class,700000,null);

        createBeanChangeFunction(PushTaskDO.class, "pushTaskDTO", false);
//        createBeanChangeFunction(ForwarderReceiveProductDTO.class,"forwarderReceiveProductDO",false);

//        createBeanChangeFunction(WarehouseReceiveNoteDO.class,"warehouseReceiveNoteDTO",false);
//        createBeanChangeFunction(OrderStatisticsDO.class,"orderStatisticsInfo",false);

//        createBeanChangeFunction(RefundOrderDO.class,"refundOrderDTO",false);

        /*str("object_id,space_code,content_type,biz_Data,content,href_url,status,priority,source,gmt_start,gmt_end,app_os_type,app_min_version,app_max_version,color,crontab_type,crontab_json,env_type,tnt_inst_id,ext_info,gmt_create,gmt_modified",
                ",");*/
        //claasEncapsulationMap(CdpContentDO.class,false);

        //System.out.println(getSmallClassName(CdpContentDO.class));

        /*String str = "contentType: '',\n"
                + "      spaceCode: '',\n"
                + "      bizData: '',\n"
                + "      content: '',\n"
                + "      hrefUrl: '',\n"
                + "      source: '',\n"
                + "      status: '',\n"
                + "      priority: '',\n"
                + "      startTime: '',\n"
                + "      endTime: '',\n"
                + "      appOsType: '',\n"
                + "      appMinVersion: '',\n"
                + "      appMaxVersion: '',\n"
                + "      color: '',\n"
                + "      crontabType: '',\n"
                + "      crontabJson: '',\n"
                + "      spmId: '',\n"
                + "      envType: '',\n"
                + "      tntInstId: '',\n"
                + "      extInfo: '',";

        str = "spaceCode: '',\n"
                + "      spaceName: '',\n"
                + "      type: '',\n"
                + "      status: '',\n"
                + "      bizData: '',\n"
                + "      accessWay: '',\n"
                + "      updatePolicy: '',\n"
                + "      multiStyle: '',\n"
                + "      rotationTime: '',\n"
                + "      displayMaxCount: '',\n"
                + "      location: '',\n"
                + "      height: '',\n"
                + "      width: '',\n"
                + "      iosViewId: '',\n"
                + "      androidViewId: '',\n"
                + "      h5ViewId: '',\n"
                + "      tntInstId:'',\n"
                + "      spmId:'',";

        System.out.println(str);

        System.out.println("=================================");

        strAppend(str,":","params.",",");

        System.out.println("=================================");

        strAppend(str,":","this.state.",",");

        System.out.println("=================================");

        strAppend(str,":","data.cdp_content.",",");

        System.out.println("=================================");

        String str2 = "contentId={paramContentId}\n"
                + "              contentName={this.state.contentName}\n"
                + "              contentType={this.state.contentType}\n"
                + "              spaceCode={this.state.spaceCode}\n"
                + "              contentValue={this.state.contentValue}\n"
                + "              redirectUrl={this.state.redirectUrl}\n"
                + "              envType={this.state.envType}\n"
                + "              statusType={this.state.statusType}\n"
                + "              effectiveDate={parseInt(this.state.effectiveDate, 10)}\n"
                + "              expireDate={parseInt(this.state.expireDate, 10)}\n"
                + "              extendInfo={this.state.extendInfo}\n"
                + "              language={this.state.language}\n"
                + "              order={parseInt(this.state.order, 10)}\n"
                + "              priority={parseInt(this.state.priority, 10)}\n"
                + "              selectRule={this.state.selectRule}\n"
                + "              onSubmit={this.onSubmit.bind(this)}\n"
                + "              isNew={this.state.isNew}\n"
                + "              successProcess={this.state.successProcess}";

        strAppend(str,"=","{this.state.","}");

        System.out.println("=================================");

        strAppend(str,":","nextProps.data.",",");

        System.out.println("=================================");

        DaoUtil.propertieStart="Input";

        strAppend(str,":","nextProps.data.",",");

        System.out.println("=================================");*/
    }
}